package com.checkbox.widgetset;

import com.checkbox.widgetset.client.share.SelectableTreeState;
import com.vaadin.server.Resource;
import com.vaadin.server.ResourceReference;
import com.vaadin.ui.AbstractComponentContainer;
import com.vaadin.ui.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("serial")
public class SelectableTree extends AbstractComponentContainer {
  private final List<Component> childList = new LinkedList<Component>();

  public SelectableTree() {
  }

  public SelectableTreeNode addChild(Object itemId, Object data) {
    return addChild(itemId, null, data);
  }

  public SelectableTreeNode addChild(Object itemId, String displayStr, Object data) {
    SelectableTreeNode newChild = new SelectableTreeNode(itemId, displayStr, data);
    this.addComponent(newChild);
    return newChild;
  }

  @Override
  public void addComponent(Component component) {
    if (component instanceof SelectableTreeNode) {
      this.childList.add(component);
      super.addComponent(component);
    }
  }

  public void clearSelected() {
    for (Component c : this.childList) {
      SelectableTreeNode node = (SelectableTreeNode) c;
      node.clearSelect();
    }
  }

  @Override
  public int getComponentCount() {
    return childList.size();
  }

  @Override
  public Iterator<Component> getComponentIterator() {
    return this.childList.iterator();
  }

  public List<Object> getSelectedItems() {
    List<Object> ret = new ArrayList<Object>();
    for (Component child : this.childList) {
      SelectableTreeNode node = (SelectableTreeNode) child;
      if (node.isSelect()) {
        ret.add(node.getItemId());
      }
      ret.addAll(node.getSelectedChildren());
    }
    return ret;
  }

  @Override
  public Iterator<Component> iterator() {
    return childList.iterator();
  }

  public void removeAllChildren() {
    this.childList.clear();
    super.removeAllComponents();
  }

  public void removeChild(SelectableTreeNode child) {
    removeComponent(child);
  }

  @Override
  public void removeComponent(Component c) {
    if (this.childList.remove(c)) {
      super.removeComponent(c);
    }
  }

  @Override
  public void replaceComponent(Component oldComponent, Component newComponent) {
    // TODO Auto-generated method stub
  }

  public void setCollapseImage(Resource image) {
    ResourceReference ref = null;
    if (image != null) {
      ref = ResourceReference.create(image, this, null);
    }
    getState().collapseIcon = ref;
  }

  public void setExpandImage(Resource image) {
    ResourceReference ref = null;
    if (image != null) {
      ref = ResourceReference.create(image, this, null);
    }
    getState().expandIcon = ref;
  }

  @Override
  protected SelectableTreeState getState() {
    return (SelectableTreeState) super.getState();
  }
}
